package com.lwlk.zdk.controller.Assess;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lwlk.zdk.annotation.MyLog;
import com.lwlk.zdk.enums.RetCode;
import com.lwlk.zdk.mapper.T.*;
import com.lwlk.zdk.mapper.pw.pwAssessGradeIndexMapper;
import com.lwlk.zdk.mapper.pw.pwAssessGradeMapper;
import com.lwlk.zdk.mapper.pw.pwUserMapper;
import com.lwlk.zdk.mapper.sys.sysEnterpriseMapper;
import com.lwlk.zdk.mapper.sys.sysUserMapper;
import com.lwlk.zdk.mapper.wd.wdHfAreaMapper;
import com.lwlk.zdk.mapper.wd.wdIndustryDictionaryMapper;
import com.lwlk.zdk.model.CommonUser;
import com.lwlk.zdk.model.Encapsulation.EncapsuationAssessObject;
import com.lwlk.zdk.model.Encapsulation.EncapsulationAssess;
import com.lwlk.zdk.model.Encapsulation.EncapsulationScore;
import com.lwlk.zdk.model.T.TRegion;
import com.lwlk.zdk.model.pw.pwAssessGrade;
import com.lwlk.zdk.model.pw.pwAssessGradeIndex;
import com.lwlk.zdk.model.task.pwTaskPlatformAssessmentStatistics;
import com.lwlk.zdk.util.JwtTokenUtil;
import com.lwlk.zdk.util.LayuiTablePagingResult;
import com.lwlk.zdk.util.Response;
import com.lwlk.zdk.util.listerUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.print.DocFlavor;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/*
* 考核指标得分规则
* */
@RestController
@RequestMapping(value = "/assess")
@Transactional
public class AssessRuleController {


    @Autowired
    pwAssessGradeMapper pwAssessGradeMapper;
    @Autowired
    pwAssessGradeIndexMapper pwAssessGradeIndexMapper;
    @Autowired
    TDisVehicleMapper disVehicleMapper;
    @Autowired
    TDisPlatformMapper disPlatformMapper;
    @Autowired
    TDisEnterpriseMapper disEnterpriseMapper;
    @Autowired
    TRegionMapper tRegionMapper;
    @Autowired
    TDisDictionaryMapper disDictionaryMapper;
    @Autowired
    private pwUserMapper pwUserMapper;



    @ApiOperation(value = "根据考核类型(下级平台或运输企业)查询考核对象")
    @ApiImplicitParams({@ApiImplicitParam(name = "lowerPlatform",value = "下级平台",paramType = "query"),
            @ApiImplicitParam(name = "transportEnterprise",value = "运输企业",paramType = "query"),
            @ApiImplicitParam(name = "regionCode",value = "地区码",paramType = "query",required=true),
            @ApiImplicitParam(name = "administration",value = "管辖机构",paramType = "query"),
            @ApiImplicitParam(name = "platformId",value = "平台id",paramType = "query"),
            @ApiImplicitParam(name = "parentId",value = "地区父节点",paramType = "query")})
    @RequestMapping(value = "/showAssessObject",method = RequestMethod.GET)
    public LayuiTablePagingResult getAssessObject(String lowerPlatform,String transportEnterprise,String administration,Integer platformId,String regionCode,Integer parentId,Integer level,Integer page,Integer size){
      LayuiTablePagingResult result=null;
      try {
          PageHelper.startPage(page,size);
          Integer areaCode=null;
          if (level==1){
              areaCode= Integer.valueOf(String.valueOf(regionCode).substring(0,2));
          }else if (level==2){
              areaCode= Integer.valueOf(String.valueOf(regionCode).substring(0,4));
          }else if (level==3){
              areaCode= Integer.valueOf(regionCode);
          }
          if (lowerPlatform.equals("1")){//查询下级平台
              //查询下级平台
              List<Map<String, Object>> platformList = disPlatformMapper.searchFQ();
              PageInfo pageInfo=new PageInfo<>(platformList);
              result = new LayuiTablePagingResult();
              result.setCode(RetCode.SUCCESS.getCode());
              result.setMsg(RetCode.SUCCESS.getMsg());
              result.setCount(pageInfo.getTotal());
              result.setData(pageInfo.getList());
              Long totalPages = pageInfo.getTotal() / size;
              if (pageInfo.getTotal() % size != 0){
                  totalPages ++;
              }
              result.setTotalPages(totalPages);
             return result;
          }
           if (lowerPlatform.equals("2")){//如果查询运输企业
              List<Map<String,Object>>enterpriseList=disEnterpriseMapper.selectEnterpriseList(areaCode);
               PageInfo pageInfo=new PageInfo<>(enterpriseList);
               result = new LayuiTablePagingResult();
               result.setCode(RetCode.SUCCESS.getCode());
               result.setMsg(RetCode.SUCCESS.getMsg());
               result.setCount(pageInfo.getTotal());
               result.setData(pageInfo.getList());
               Long totalPages = pageInfo.getTotal() / size;
               if (pageInfo.getTotal() % size != 0){
                   totalPages ++;
               }
               result.setTotalPages(totalPages);
               return result;
          }
           if (lowerPlatform.equals("0")){//如果查询管辖机构
               List<Map<String,Object>>administrationList=tRegionMapper.selectByArea(parentId);
               PageInfo pageInfo=new PageInfo<>(administrationList);
               result = new LayuiTablePagingResult();
               result.setCode(RetCode.SUCCESS.getCode());
               result.setMsg(RetCode.SUCCESS.getMsg());
               result.setCount(pageInfo.getTotal());
               result.setData(pageInfo.getList());
               Long totalPages = pageInfo.getTotal() / size;
               if (pageInfo.getTotal() % size != 0){
                   totalPages ++;
               }
               result.setTotalPages(totalPages);
               return result;
           }
      }catch (Exception e){
          e.printStackTrace();
      }
      return result;
    }



    @ApiOperation(value = "展示区县考核对象")
    @ApiImplicitParams({@ApiImplicitParam(name = "areaCode",value = "地区码",paramType = "query",required=true)})
    @RequestMapping(value = "/countyObject",method = RequestMethod.GET)
    public Response getCountyObject(String areaCode){
        Response response=new Response();
        List<Map<String,Object>>areaCodeList=tRegionMapper.selectByCode(areaCode);
        response.setData(areaCodeList);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }




    @ApiOperation(value = "添加考核规则")
    @RequestMapping(value = "/addAssess",method = RequestMethod.POST)
    public Response getAssess(@RequestBody EncapsulationScore es, HttpServletRequest request){
        Response response=new Response();
        try {
            boolean flag= listerUtil.getLister(request);
            if (flag==false){
                response.setCode(RetCode.ACCOUNT_EXIST);
                response.setMsg("此账号为监管员账号,不可进行操作");
                return response;
            }
            //判断:如果此类考核周期已有,则返回
            //int count=pwAssessGradeMapper.selectByAssessPeriod(es.getAssessPeriod(),es.getAssessType());
            /*if (count>0){
                response.setCode(RetCode.NOTNULL);
                return response;
            }*/
            pwAssessGrade pwAssessGrade=new pwAssessGrade();
            pwAssessGrade.setAssessName(es.getAssessName());//考核名称
            pwAssessGrade.setAssessPeriod(es.getAssessPeriod());//考核周期
            pwAssessGrade.setAssessNumber(es.getAssessNumber());//考核编号
            pwAssessGrade.setAssessType(es.getAssessType());//考核类型
            pwAssessGrade.setAssessStandard(es.getAssessStandard());//考核标准
            pwAssessGrade.setAssessFounder(es.getAssessFounder());//考核方案创建者
            pwAssessGrade.setAssessObject(es.getAssessObject());//考核对象
            pwAssessGrade.setPlatformId(es.getPlatformId());//平台id
            //添加考核评分规则表数据
            int id=pwAssessGradeMapper.insertSelective(pwAssessGrade);//获取主键id
            List<pwAssessGradeIndex> pwAssessGradeIndex=es.getPwAssessGradeIndex();
            for (int i = 0; i < pwAssessGradeIndex.size(); i++) {
                pwAssessGradeIndex pwAssessGradeIndex1=new pwAssessGradeIndex();
                pwAssessGradeIndex1.setAssessGradeId(pwAssessGrade.getId());//考核评分规则表id
                pwAssessGradeIndex1.setIndexName(pwAssessGradeIndex.get(i).getIndexName());//指标名称
                pwAssessGradeIndex1.setPercentagePoints(pwAssessGradeIndex.get(i).getPercentagePoints());//扣分比例
                pwAssessGradeIndex1.setLowestMarkRatio(pwAssessGradeIndex.get(i).getLowestMarkRatio());//不得分比例
                if (Integer.parseInt(pwAssessGradeIndex1.getPercentagePoints())<Integer.parseInt(pwAssessGradeIndex1.getLowestMarkRatio())){
                    int count=pwAssessGradeMapper.deleteByPrimaryKey(pwAssessGrade.getId());
                    response.setCode(RetCode.REQUEST_ERROR);
                    response.setMsg("扣分比例不可小于不得分比例");
                    return response;
                }
                pwAssessGradeIndex1.setScore(pwAssessGradeIndex.get(i).getScore());//分数
                pwAssessGradeIndex1.setScoreExplain(pwAssessGradeIndex.get(i).getScoreExplain());//分数说明
                pwAssessGradeIndexMapper.insertSelective(pwAssessGradeIndex1);
            }
            response.setCode(RetCode.SUCCESS);
            response.setMsg("执行成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }

    @ApiOperation(value = "考核编码唯一")
    @RequestMapping(value = "/assessNumberSole",method = RequestMethod.GET)
    public Response getAssessNumberSole(String assessNumber){
        Response response=new Response();
        int count=pwAssessGradeMapper.selectNumberOne(assessNumber);
        if (count>0){
            response.setCode(RetCode.ENTERPRISE_EXIST);
            response.setMsg("所填考核编码已存在,请重新填写");
        }
        return response;
    }

    @ApiOperation(value = "展示考核规则(根据考核id)")
    @ApiImplicitParams({@ApiImplicitParam(name = "assessId",value = "考核id",paramType = "query",required=true)})
    @RequestMapping(value = "/showAssess",method =RequestMethod.GET)
    public Response getAssess(Integer assessId){
      Response response=new Response();
      try {
          List<EncapsulationAssess>Assess=pwAssessGradeMapper.selectAssess(assessId);
          String assessObjectName="";
          for (int i = 0; i < Assess.size(); i++) {
              //考核类型
              String assessType=Assess.get(i).getAssesstype();
              if (Assess.get(i).getAssessobject()!=null){
                  String[] assessObject=Assess.get(i).getAssessobject().split(",");
                  if (assessType.equals("0")){
                      //查询管辖机构名称
                      for (String regionId : assessObject) {
                          assessObjectName +=tRegionMapper.selectName(Integer.valueOf(regionId))+",";
                      }
                  }
                  if (assessType.equals("1")){
                      //查询下级平台名称
                      for (String platformId : assessObject) {
                          assessObjectName +=disPlatformMapper.selectpId(Integer.valueOf(platformId))+",";
                      }
                  }
                  if (assessObject.equals("2")){
                      //查询下级平台名称
                      for (String enterpriseId : assessObject) {
                          assessObjectName += disEnterpriseMapper.selectByEid(Integer.valueOf(enterpriseId))+",";
                      }
                  }
                  String[] objectName=assessObjectName.split(",");
                  Assess.get(i).setAssessobject(Arrays.toString(objectName).replace("[","").replace("]",""));
              }else {
                  Assess.get(i).setAssessobject(null);
              }

      }
          response.setData(Assess);
          response.setCode(RetCode.SUCCESS);
          response.setMsg("执行成功");
      }catch (Exception e){
          e.printStackTrace();
      }
      return response;
    }

    @ApiOperation(value = "展示考核对象")
    @RequestMapping(value = "/assessObject",method = RequestMethod.GET)
    public Response getAssessObject(Integer assessId){
        Response response=new Response();
        try {
            List<EncapsulationAssess>Assess=pwAssessGradeMapper.selectAssess(assessId);
            List<EncapsuationAssessObject>assessObjectList=new ArrayList<>();
            String assessObjectName="";
                //考核类型
                //String assessType=Assess.get(i).getAssesstype();
                if (Assess.get(0).getAssessobject()!=null){
                    String[] assessObject=Assess.get(0).getAssessobject().split(",");
                    if (Assess.get(0).getAssesstype().equals("0")){
                        //查询管辖机构名称
                        for (String regionId : assessObject) {
                            TRegion tregion =tRegionMapper.selectTRegion(Integer.valueOf(regionId));
                            EncapsuationAssessObject encapsuationAssessObject=new EncapsuationAssessObject();
                            encapsuationAssessObject.setId(Integer.parseInt(regionId));
                            encapsuationAssessObject.setAssessObjectName(tregion.getName());
                            assessObjectList.add(encapsuationAssessObject);
                        }
                    }
                    if (Assess.get(0).getAssesstype().equals("1")){
                        //查询下级平台名称
                        for (String platformId : assessObject) {
                            assessObjectName =disPlatformMapper.selectpId(Integer.valueOf(platformId));
                            EncapsuationAssessObject encapsuationAssessObject=new EncapsuationAssessObject();
                            encapsuationAssessObject.setId(Integer.parseInt(platformId));
                            encapsuationAssessObject.setAssessObjectName(assessObjectName);
                            assessObjectList.add(encapsuationAssessObject);

                        }
                    }
                    if (Assess.get(0).getAssesstype().equals("2")){
                        //查询业户名称
                        for (String enterpriseId : assessObject) {
                            assessObjectName = disEnterpriseMapper.selectByEid(Integer.valueOf(enterpriseId));
                            EncapsuationAssessObject encapsuationAssessObject=new EncapsuationAssessObject();
                            encapsuationAssessObject.setId(Integer.parseInt(enterpriseId));
                            encapsuationAssessObject.setAssessObjectName(assessObjectName);
                            assessObjectList.add(encapsuationAssessObject);
                        }
                    }
                    response.setData(assessObjectList);
                }

            response.setCode(RetCode.SUCCESS);
            response.setMsg("执行成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }


    @ApiOperation(value = "展示考核规则(所有的)")
    @RequestMapping(value = "/showAssessAll",method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "platformId",value = "平台id",paramType = "query",required=true),
            @ApiImplicitParam(name = "assessName",value = "考核名称",paramType = "query"),
            @ApiImplicitParam(name = "assessPeriod",value = "考核周期(0:日考核1:周考核2:月考核3:年考核)",paramType = "query",required=true),
            @ApiImplicitParam(name = "assessType",value = "考核类型(0:管辖机构1下级平台:2:运输企业)",paramType = "query",required=true)})
    public LayuiTablePagingResult getAssessAll(Integer platformId, String assessName,Integer page, Integer size,String assessPeriod,String assessType){
        LayuiTablePagingResult result=null;
        try {
               PageHelper.startPage(page,size);
               List<Map<String,Object>>assessAll=pwAssessGradeMapper.selectAssessAll(platformId,assessName,assessPeriod,assessType);
            PageInfo<pwTaskPlatformAssessmentStatistics> pageInfo=new PageInfo(assessAll);
            result = new LayuiTablePagingResult();
            result.setCode(RetCode.SUCCESS.getCode());
            result.setMsg(RetCode.SUCCESS.getMsg());
            result.setCount(pageInfo.getTotal());
            result.setData(pageInfo.getList());
            Long totalPages = pageInfo.getTotal() / size;
            if (pageInfo.getTotal() % size != 0){
                totalPages ++;
            }
            result.setTotalPages(totalPages);

        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    @ApiOperation(value = "展示考核规则(所有的)不分页")
    @RequestMapping(value = "/showAssessAllNoPage",method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "platformId",value = "用户id",paramType = "query",required=true),
            @ApiImplicitParam(name = "assessName",value = "考核名称",paramType = "query"),
            @ApiImplicitParam(name = "assessPeriod",value = "考核周期(0:日考核1:周考核2:月考核3:年考核)",paramType = "query",required=true),
            @ApiImplicitParam(name = "assessType",value = "考核类型(0:管辖机构1下级平台:2:运输企业)",paramType = "query",required=true)})
    public Response getAssessAll(Integer platformId,String assessName,String assessPeriod,String assessType){
        Response response=new Response();
        try {
            List<Map<String,Object>>assessAll=pwAssessGradeMapper.selectAssessAll(platformId,assessName,assessPeriod,assessType);
            response.setData(assessAll);
            response.setCode(RetCode.SUCCESS);
            response.setMsg("执行成功");

        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }

    @ApiOperation(value = "修改考核规则")
    @RequestMapping(value = "/updateAssess",method = RequestMethod.POST)
    public Response getUpdateAssess(@RequestBody pwAssessGrade pwAssessGrade, List<pwAssessGradeIndex> pwAssessGradeIndex,HttpServletRequest request){
        Response response=new Response();
        try {
            boolean flag= listerUtil.getLister(request);
            if (flag==false){
                response.setCode(RetCode.ACCOUNT_EXIST);
                response.setMsg("此账号为监管员账号,不可进行操作");
                return response;
            }
                int i=pwAssessGradeMapper.updateByPrimaryKeySelective(pwAssessGrade);
            for (pwAssessGradeIndex assessGradeIndex : pwAssessGradeIndex) {
                int s=pwAssessGradeIndexMapper.updateByPrimaryKeySelective(assessGradeIndex);
                response.setData(1);
                response.setCode(RetCode.SUCCESS);
                return response;
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }



    @ApiOperation(value = "展示考核周期")
    @RequestMapping(value = "/showPeriod",method = RequestMethod.GET)
    public Response showPeriod(){
        Response response=new Response();
        List<Map<String,Object>> assessPeriod=disDictionaryMapper.selectAssessPeriod();
        response.setData(assessPeriod);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        return response;
    }

    @ApiOperation(value = "删除考核规则")
    @MyLog(value = "删除考核规则")
    @ApiImplicitParams({@ApiImplicitParam(name = "id",value = "考核规则id",paramType = "query",required=true)})
    @RequestMapping(value = "/deleteAssess",method = RequestMethod.DELETE)
    public Response deleteAssess(Integer id,HttpServletRequest request){
        Response response=new Response();
        boolean flag= listerUtil.getLister(request);
        if (flag==false){
            response.setCode(RetCode.ACCOUNT_EXIST);
            response.setMsg("此账号为监管员账号,不可进行操作");
            return response;
        }
        int i=pwAssessGradeMapper.deleteByPrimaryKey(id);
        int b=pwAssessGradeIndexMapper.deleteByPrimaryKey(id);
        response.setCode(RetCode.SUCCESS);
        response.setMsg("执行成功");
        response.setData(i);
        return response;
    }



}
